package com.cf.wmsg.model;

import cn.hutool.core.collection.CollUtil;
import com.cf.crud.service.AbsBaseService;
import com.cf.id.SnowflakeId;
import com.cf.mapper.BeanMapper;
import com.cf.user.login.model.UserInfo;
import com.cf.user.login.service.UserInfoService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedList;
import java.util.List;

/**
 * boot-message-WebMessageService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/7/12 下午 03:03
 */
public class WebMessageService extends AbsBaseService<WebMessage, WebMessageDao> {
    @Override
    public Class getTargetClass() {
        return WebMessage.class;
    }

    @Autowired
    private SnowflakeId id;

    @Autowired
    private BeanMapper beanMapper;

    @Autowired
    private UserInfoService userInfoService;

    public void sendToAllUser(WebMessage webMessage) {
        List<UserInfo> userInfos = userInfoService.selectAll();
        List<List<UserInfo>> split = CollUtil.split(userInfos, 100);
        split.forEach(ufs -> {
            if (ufs != null && ufs.size() > 0) {
                List<WebMessage> webMessages = new LinkedList<>();
                ufs.stream().forEach(userInfo -> {
                    WebMessage wm = beanMapper.map(webMessage, WebMessage.class);
                    wm.setId(id.nextId());
                    wm.setUserId(userInfo.getId());
                    webMessages.add(wm);
                });
                this.mapper.insertListWithId(webMessages);
            }
        });
    }

    public WebMessage getChatMessageByBizId(String type, String bizId) {
        return this.mapper.selectByTypeAndBzData(type, bizId);
    }

    public Page<WebMessage> getUserMessage(long userId, int page, int size) {
        PageHelper.startPage(page, size);
        PageHelper.orderBy(" addTime desc ");
        return this.mapper.selectByUser(userId);
    }

    public Boolean watch(long messageId, long userId) {
        int num = this.mapper.watch(messageId, userId);
        return num > 0;
    }

    public Boolean delWebMessage(long messageId, long userId) {
        int num = this.mapper.deleteByPrimaryKeyAndUserId(messageId, userId);
        return num > 0;
    }
}
